package cn._51doit.day09;


import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @create: 2021-10-26 19:29
 * @author: 今晚打脑斧先森
 * @program: keyedStreamUseKeyedState
 * @Description:
 *    2.使用ProcessFunction的状态（只能针对与KeyedStream）
 *    在KeyedStream中 使用 KeyedProcessFunction，并且使用状态（KeyedState）
 **/
public class keyedStreamUseKeyedState {
    public static void main(String[] args) throws Exception {
        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port",8081);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(configuration);
        env.enableCheckpointing(10000);//开启checkpoint,默认无限重启

        DataStreamSource<String> lines = env.socketTextStream("doit01", 8888);
        //对数据进行切割处理
        SingleOutputStreamOperator<Tuple2<String, Integer>> mapped = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] split = value.split(",");
                if (split[0].startsWith("error")) {
                    throw new RuntimeException("亲爱的今晚打脑斧先森,数据出错了哦");
                }
                return Tuple2.of(split[0],Integer.parseInt(split[1]));
            }
        });
        //分区
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = mapped.keyBy(t -> t.f0);
        SingleOutputStreamOperator<Tuple2<String, Integer>> res = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {
            private transient ValueState<Integer> valueState; //单词个数状态

            @Override
            public void open(Configuration parameters) throws Exception {
                //状态描述器
                ValueStateDescriptor<Integer> descriptor = new ValueStateDescriptor<>("单词的个数", Integer.class);
                //获取状态
                valueState = getRuntimeContext().getState(descriptor);
            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                String word = value.f0;
                Integer currentCount = value.f1;
                Integer historyCount = valueState.value();
                if (historyCount == null) {
                    historyCount = 0;
                }
                currentCount += historyCount;
                valueState.update(currentCount);
                value.f1 = currentCount;
                out.collect(value);
            }
        });
        res.print();
        env.execute();
    }
}
